package io.cici.cc.mybatis.lite.sql_source;

import io.cici.cc.mybatis.lite.mapping.Sql;
import io.cici.cc.mybatis.lite.mapping.SqlSource;
import io.cici.cc.mybatis.lite.session.Configuration;
import io.cici.cc.mybatis.lite.sql_source.scripting.tag.Tag;

import java.util.HashMap;


public class RawSqlSource implements SqlSource {

    private final SqlSource sqlSource;

    public RawSqlSource(Configuration configuration, Tag rootTag, Class<?> parameterType) {
        this(configuration, getSql(configuration, rootTag), parameterType);
    }

    public RawSqlSource(Configuration configuration, String sql, Class<?> parameterType) {
        SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
        Class<?> clazz = parameterType == null ? Object.class : parameterType;
        sqlSource = sqlSourceParser.parse(sql, clazz, new HashMap<>());
    }

    private static String getSql(Configuration configuration, Tag tag) {
        Context context = new Context(configuration, null);
        tag.apply(context);
        return context.getSql();
    }

    @Override
    public Sql getSql(Object parameterObject) {
        return sqlSource.getSql(parameterObject);
    }

}
